﻿using fuzhu;
using LH.U8API.Bus; 
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using LH.Model.SA;
using ZDEntity; 
using System.Diagnostics.Eventing.Reader;
using System.DirectoryServices.ActiveDirectory;
using System.Reflection;
using System.Security.Cryptography;
using System.Xml.Linq;
using XXX.Models.PU;
using LH.Model.PU;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore.Metadata;
using XXX.Models.XXXEntities;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class PuAppVouchVM : PuAppVouch
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        //公司名称
        public string cAccount { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public PuAppVouchVM(PuAppVouchHead head, List<PuAppVouchBody> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }
        
        /// <summary>
        /// 传入json转换成PuAppVouchVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public PuAppVouchVM GetEntity(HuaJin_AppVouch obj, ref string cErr, ref string cCode)
        {

            try
            { 
              

                

                cCode = obj.cCode;
                if (string.IsNullOrWhiteSpace(obj.cMaker))
                {
                    cErr = "制单人不能为空";
                    return null;
                }
                if (string.IsNullOrWhiteSpace(obj.cVerifier))
                {
                    cErr = "审核人不能为空";
                    return null;
                }
                //if (string.IsNullOrWhiteSpace(obj.cAuditDate))
                //{
                //    cErr = "审核日期不能为空";
                //    return null;
                //}


                PuAppVouch.PuAppVouchHead head = new PuAppVouch.PuAppVouchHead
                {
                    ccode = obj.cCode,
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cdepcode = obj.cDepCode,
                    cpersoncode = obj.cPersonCode,
                    cmaker = obj.cMaker,
                    cauditdate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cverifier = obj.cVerifier,
                    cmemo = obj.cMemo,
                    cbustype = "普通采购",
                    cptcode = obj.cPTCode,
                    iswfcontrolled = "0",
                    ivtid = "8171",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                    //chdefine7 = obj.cHDefine7,
                    //chdefine8 = obj.cHDefine8,
                    //chdefine11  = obj.cHDefine11,
                    //chdefine12 = obj.cHDefine12,


                };


                 
               

                List<PuAppVouch.PuAppVouchBody> bodies = new List<PuAppVouch.PuAppVouchBody>();

                if (obj.itemList != null && obj.itemList.Count > 0)
                {

                    int i = 0;
                    foreach (var item in obj.itemList)
                    {
                        if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                        {
                            throw new Exception("数量不能为空");
                        }
                        if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                        {
                            throw new Exception("存货编码不能为空");
                        }
                        if (string.IsNullOrEmpty(DbHelper.GetDbString(item.dArriveDate)))
                        {
                            throw new Exception("预计到货日期不能为空");
                        }
                        i++;

                        

                        PuAppVouch.PuAppVouchBody body = new PuAppVouch.PuAppVouchBody
                        {

                            cinvcode = item.cInvCode,
                            //cfree1 = item.cFree1,
                            //cfree2 = item.cFree2,
                            //cfree3 = item.cFree3,
                            //cfree4 = item.cFree4,
                            ivouchrowno = (i*10).ToString(),
                            fquantity = DbHelper.GetDbdecimal(item.iQuantity),
                            cbmemo = item.cBMemo,
                            darrivedate = DbHelper.GetDbDate(item.dArriveDate).ToString("yyyy-MM-dd"),
                            drequirdate = DbHelper.GetDbDate(item.dArriveDate).ToString("yyyy-MM-dd"),                           
                            ipertaxrate = DbHelper.GetDbdecimal(item.iPerTaxRate),
                            iexchrate = item.iExchrate ,
                            cexch_name = item.cExchname,
                            citemcode = item.cItemCode,
                            citemname = item.cItemName,
                            citem_class = item.cItem_Class,
                            citem_name = item.cItem_Name,
                           ////本币价格
                           // funitprice  = item.iNatUnitPrice,
                           // ftaxprice = item.iNatTaxUnitPrice,
                           // //含税金额
                           // fmoney  = item.iNatSum,
                           // //无税金额
                           // imoney = DbHelper.GetDbString(item.iNatMoney),
                            //原币价格
                            //ioritaxcost = DbHelper.GetDbString(item.iOriTaxUnitPrice),
                            ioricost = item.iOriUnitPrice,
                            iorimoney = item.iOriMoney, 
                           // iorisum= DbHelper.GetDbString(item.iOriSum),
                           ////税额
                           // itaxprice= DbHelper.GetDbString(item.iNatTax),
                           // ioritaxprice = DbHelper.GetDbString(item.iOriTax), 
 
                        //从22 写到37
                            cdefine22 = item.cDefine22,
                            cdefine23 = item.cDefine23,
                            cdefine24 = item.cDefine24,
                            cdefine25 = item.cDefine25,
                            cdefine26 = item.cDefine26,
                            cdefine27 = item.cDefine27,
                            cdefine28 = item.cDefine28,
                            cdefine29 = item.cDefine29,
                            cdefine30 = item.cDefine30,
                            //OA的表体id
                            cdefine31 = item.cDefine31,
                            cdefine32 = item.cDefine32,
                            cdefine33 = item.cDefine33,
                            cdefine34 = item.cDefine34,
                            cdefine35 = item.cDefine35,
                            cdefine36 = item.cDefine36,
                            cdefine37 = item.cDefine37
                            //cdefine33  = item.bid,
                        };
                        if (string.IsNullOrEmpty(item.cExchname))
                        {
                            body.cexch_name = "人民币";
                        }
                        //如果税率是空，并且币种= 人民币，税率=13
                        if (body.cexch_name == "人民币" && string.IsNullOrWhiteSpace(item.iPerTaxRate))
                        {
                            body.ipertaxrate =13.00m;
                        }
                        if (body.cexch_name == "人民币" && string.IsNullOrWhiteSpace(DbHelper.GetDbString(item.iExchrate)))
                        {
                            body.iexchrate =1.00m;
                        }
                        #region 处理单价问题，根据 原币无税单价 原币无税金额反算

                        //先算含税金额
                        if (item.iOriUnitPrice != null && item.iOriMoney != null)
                        {
                            decimal dOriSum = Math.Round((decimal)item.iOriMoney * (1 + (decimal)body.ipertaxrate / 100), 2);
                            decimal dOriTax = dOriSum - (decimal)item.iOriMoney;
                            decimal dOriTaxUnitPrice = Math.Round(dOriSum / (decimal)item.iQuantity, 6);

                            body.iorisum = dOriSum;
                            body.ioritaxprice = dOriTax;
                            //原币价格
                            body.ioritaxcost = dOriTaxUnitPrice;
                            ////本币价格

                            body.funitprice = Math.Round((decimal)item.iOriUnitPrice * DbHelper.GetDbdecimal(body.iexchrate), 2);
                            body.ftaxprice = Math.Round(dOriTaxUnitPrice * DbHelper.GetDbdecimal(body.iexchrate), 2);
                            body.fmoney = Math.Round(dOriSum * DbHelper.GetDbdecimal(body.iexchrate), 2);
                            body.imoney = Math.Round((decimal)item.iOriMoney * DbHelper.GetDbdecimal(body.iexchrate), 2);
                            body.ioritaxprice = Math.Round(dOriTax * DbHelper.GetDbdecimal(body.iexchrate), 2);
                        }

                        
                        // //含税金额
                        // fmoney  = item.iNatSum,
                        // //无税金额
                        // imoney = DbHelper.GetDbString(item.iNatMoney),
                        //原币价格
                        //ioritaxcost = DbHelper.GetDbString(item.iOriTaxUnitPrice),


                        ////税额
                        // itaxprice= DbHelper.GetDbString(item.iNatTax),
                        // ioritaxprice = DbHelper.GetDbString(item.iOriTax), 
                         
                        #endregion

                        bodies.Add(body);
                    }
                }
                this.head = head;
                this.bodies = bodies;
                //PuAppVouchVM model = new PuAppVouchVM(head, bodies);

                return this;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }

        public  RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrorObject("当前请购单号已存在" );
                }
                foreach(PuAppVouchBody body in bodies)
                {
                    body.editprop = "A";
                }
            
                string cRe = GetPuappInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrorObject("获取基础信息失败：" + cRe);
                }
              
                //直接赋值了审核人，所以不需要再审核了
                if (!Pu_AppVouchDALCO.AddPu_AppVouch(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //这个提示也认为是成功的
                    if (err== "add 下标越界")
                    {
                        return DBService.ReOKObject(ccode);
                    }
                    else
                    {
                        return DBService.ReErrorObject("新增失败：" + err);
                    }
                    
                }
             
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrorObject(ex.Message);
            }



        }


        public RetModel2 Add()
        {
            try
            {
                string idcheck = ""; 
                
                if (!Pu_AppVouchDALCO.AddPu_AppVouch(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //这个提示也认为是成功的
                    if (err == "add 下标越界")
                    {
                        return DBService.ReOKObject(id);
                    }
                    else
                    {
                        return DBService.ReErrorObject("新增失败：" + err);
                    }

                }

                return DBService.ReOKObject(id);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrorObject(ex.Message);
            }



        }

        /// <summary>
        /// 完善请购信息,处理部门，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetPuappInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            { 

                //#region  根据业务员取部门编码
                //if(!string.IsNullOrWhiteSpace(head.cpersoncode))
                //{
                //    Person person =db.Queryable<Person>().Where(x => x.cPersonCode == head.cpersoncode).First();
                //    if (person == null)
                //    {
                //        return string.Format("Error: 业务员编码{0}不存在", head.cpersoncode);
                //    }
                //    else
                //    {
                //        head.cdepcode = person.cDepCode;                         
                //    }
                //}

                //#endregion

                for (int i = 0; i < bodies.Count; i++)
                {
                    string cInvCode = bodies[i].cinvcode;
                    Inventory inv = db.Queryable<Inventory>().Where(c => c.cInvCode == cInvCode).First();
                    if (inv == null)
                    {
                        return string.Format("Error: 第{0}行存货编码{1}不存在", (i + 1).ToString(), cInvCode);
                    }



                    #region 处理辅助计量单位
                    bodies[i].cgroupcode = inv.cGroupCode;
                    bodies[i].igrouptype = DbHelper.GetDbString(inv.iGroupType);
                    //cunitid 不为空，则取存货档案的辅助计量单位
                    if (string.IsNullOrWhiteSpace(bodies[i].cunitid))
                    {
                        bodies[i].cunitid = inv.cAssComUnitCode;
                    }
                    //如果igrouptype！=0，则需要获取辅助单位换算率，并计算辅助数量
                    if (DbHelper.GetDbString(inv.iGroupType) != "0")
                    {
                        //换算率是空
                        if (string.IsNullOrWhiteSpace(bodies[i].iinvexchrate))
                        {
                            //并且件数也是空,取存货档案的换算率
                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].fnum)) || bodies[i].fnum == 0)
                            {
                                //获取辅助换算率
                                ComputationUnit unit = SqlsugarHelperLK.Instance.Queryable<ComputationUnit>().Where(x => x.cComunitCode == bodies[i].cunitid).First();

                                bodies[i].iinvexchrate = DbHelper.GetDbString(unit.iChangRate);
                            }
                            else
                            {
                                //件数不为空,根据数量/件数计算换算率
                                bodies[i].iinvexchrate = (DbHelper.GetDbdecimal(bodies[i].fquantity) / DbHelper.GetDbdecimal(bodies[i].fnum)).ToString("0.000000");
                            }

                        }
                        //件数： 有换算率，并且换算率不为0，件数是空的，计算辅助数量
                        if (!string.IsNullOrWhiteSpace(bodies[i].iinvexchrate) && bodies[i].iinvexchrate != "0" && string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].fnum)))
                        {
                            //计算辅助数量, 小数位。。。。。
                            bodies[i].fnum = Math.Round(DbHelper.GetDbdecimal(bodies[i].fquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate), 6);
                        }

                    }
                    #endregion

                    //#region 处理税率,传入，不处理

                    //if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].ipertaxrate)))
                    //{
                    //     if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(inv.iTaxRate)))
                    //    {
                    //        bodies[i].ipertaxrate = DbHelper.GetDbdecimal(inv.iTaxRate);
                    //    } 
                    //}

                    //#endregion

                   

                }
            }
            
            return "ok";
        }

        /// <summary>
        /// 检查销售单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from pu_appvouch where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

         
    }
}
